/* eslint-disable no-nested-ternary */
/* eslint-disable no-plusplus */
/* eslint-disable import/extensions */
import ElEditable from '@components/el-editable';
import { throttle, isObject } from 'lodash';
import {
  submitOrderReturn,
  saveOrderReturn,
  downloadFailUploadDataTH,
  uploadReturnedProduct,
  salesReturnDetails,
  getOrderType,
  echoReturnProductList,
  getOrderAddressList
} from '@api/m_mall_web_v1.js';
import * as CONSTS from './index.const';
import { supplierAndContractComponent } from '~/components/after-sale/supplier-and-contract';
import { productsList } from '~/components/after-sale/products-list';
import invoiceInfo from '~/components/after-sale/invoice-info/index.vue';
import reason from '~/components/after-sale/reason/index.vue';
import addressFunc from '~/components/after-sale/address-func/index.vue';
import { IndexService } from './index.service';

const indexService = new IndexService();

export default {
  name: 'addReturnOrder',
  inject: ['reload'],
  provide: {
    downloadFailUploadData: downloadFailUploadDataTH,
    uploadProduct: uploadReturnedProduct,
    templateDownLoad:
      'https://mt.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/ymj205ernz710fqw3wkbq9sfcqwzlf2n.xlsx'
  },
  data() {
    return {
      ...CONSTS,
      active_index: 1,
      jsTypes: '',
      busModel: '',
      address_all: [], // 编辑时要用
      // 用于接口使用的绑定数据
      submit_data: {
        // 第一步
        supplier_id: '',
        contract_id: '',
        // 第二步类型
        return_type_name: '',
        // return_type_all: '',
        return_type: [
          {
            value: '1',
            label: '寄售退回'
          },
          {
            value: '2',
            label: '寄售消耗退回'
          }
        ],
        busModel: '',
        // 第二步产品
        return_goods: [],
        // 第二步原因
        return_reason: {
          reason_sel: '',
          reason_text: '',
          reason_imgs: [],
          reason_name: ''
        },
        // 第三步发票信息
        invoice_info: {
          receive_invoice: false,
          financial_entry: false
        },
        // 第三步地址
        full_address: {},
        orderCode: '',
        orderDetailId: '',
        orderId: '',
        order_type_key: '',
        supplier_data: {},
        contract_data: {}
      },
      address_id: '',
      // 用于页面渲染使用的数据
      render_data: {
        order_type_rows: []
      },
      // 用于各种状态的数据
      status: {
        isEdit: false,
        isFirstMount: true,
        dialogVisible: false,
        submit_loading: false
      }
    };
  },
  components: {
    ElEditable,
    supplierAndContractComponent,
    productsList,
    reason,
    invoiceInfo,
    addressFunc
  },
  mounted() {
    // 初始化导航栏按钮
    this.initGlobalBtn();
  },
  beforeRouteUpdate(to, from, next) {
    next();
    this.reload();
  },
  created() {
    this.getFullAddress();
  },
  computed: {
    routerParams() {
      return {
        orderId: this.$route.query.orderId
      };
    }
  },
  methods: {
    getFullAddress() {
      this.$axios.$post(getOrderAddressList).then(res => {
        this.address_all = res.payload || [];
        if (this.routerParams.orderId) {
          this.getDetailData();
        }
      });
    },
    getDetailData() {
      // 编辑模式
      this.$axios({
        url: salesReturnDetails,
        method: 'post',
        data: {
          orderId: this.routerParams.orderId
        }
      }).then(res => {
        const result = res.data.payload ? res.data.payload : {};
        // 其实这里直接把结果赋值给submit_data就可以了，但是为了某些更改项的对应，还是重新一一赋值一下。
        this.reRenderPage(result);
        this.getOrderTypeRowsByEdit(result);
        this.getEchoReturnProductList(result);
        // this.getReturnProductRows({ number: 1, size: 20 });
        this.status.isEdit = true;
      });
    },
    getEchoReturnProductList(result) {
      this.$axios({
        method: 'post',
        url: echoReturnProductList,
        data: {
          orderCode: result.orderData.orderCode
        }
      }).then(res => {
        const data = res.data.payload?.content;
        if (
          this.submit_data.return_type_name === '2' ||
          this.submit_data.return_type_name === ''
        ) {
          this.submit_data.return_goods = data.map(it => ({
            ...it,
            attribute1: it.model || it.specs,
            productUnitName: it.productUnit,
            productCount: Number(it.returnQuantity) || 1,
            returnCount: Number(it.returnableQuantity),
            referencePrice: it.productPrice,
            mixsIds:
              it.orginalOrderCode +
              it.seqNo +
              it.productCode +
              it.batchNo +
              it.validDate +
              it.referrencePrice
          }));
        } else {
          this.submit_data.return_goods = data.map(it => ({
            ...it,
            productCode: it.productCode,
            productName: it.productName,
            productLineName: it.productLineName,
            productUnitName: it.productUnit,
            attribute1: it.specs,
            batchNo: it.batchNo,
            referencePrice: it.referrencePrice,
            validDate: it.validDate,
            productCount: Number(it.returnQuantity) || 1,
            // returnCount: 6,
            returnCount: Number(it.returnableQuantity),
            // returnableQuantity: 6,
            mixsIds:
              it.productCode + it.batchNo + it.validDate + it.referrencePrice
          }));
        }
        this.isReturnProductsOccupy(this.submit_data.return_goods);
      });
    },
    // 判断退货产品是否被其他订单占用
    isReturnProductsOccupy(products) {
      const flag = products.some(
        item => Number(item.returnableQuantity) < Number(item.returnQuantity)
      );
      if (flag) {
        this.$alert('暂存的退货产品被别的订单使用，请订正退货产品', '', {
          confirmButtonText: '知道了',
          callback: () => {
            this.submit_data.return_goods = this.submit_data.return_goods.filter(
              item => Number(item.returnableQuantity) > 0
            );
          }
        });
      }
    },
    // 由于合同特殊性，要特别前端判断唯一性，创建contractUnitId
    getContractUnitId(item) {
      return `${item.productLineCode || ''}${item.originalFactoryCode ||
        ''}${item.channelType || ''}${item.busModel ||
        ''}${item.contractInvalidDate || ''}`;
    },
    reRenderPage(result) {
      // 设置经销商
      this.submit_data.supplier_id =
        result.orderData.supplierCode || result.orderData.originalFactoryCode;
      // 设置合同
      this.submit_data.contract_id = this.getContractUnitId(result.orderData);
      // 设置退货原因
      this.submit_data.return_reason.reason_sel =
        result.orderData.returnReasonCode;
      this.submit_data.return_reason.reason_text =
        result.orderData.returnReasonDetail;
      this.submit_data.return_reason.reason_imgs = result.commonFile.map(
        item => item.fileUrl
      );
      this.submit_data.return_type_name =
        result.jsType !== null ? result.jsType.toString() : '';
      this.jsTypes = result.jsType;
      // 设置地址
      this.address_id = result.orderReceiver.userAddressId;
      let judgeAddress = null;
      if (this.address_all.length > 0) {
        judgeAddress = this.address_all.find(
          item => item.id === result.orderReceiver.id
        );
      } else {
        judgeAddress = undefined;
      }
      if (judgeAddress !== undefined) {
        this.submit_data.full_address = {
          ...result.orderReceiver,
          userName: result.orderReceiver.addressee,
          userPhone: result.orderReceiver.addressPhone
        };
      } else {
        this.submit_data.full_address = {};
      }
      // 设置发票信息
      this.submit_data.invoice_info.receive_invoice =
        result.orderData.receiptInvoice === '1';
      this.submit_data.invoice_info.financial_entry =
        result.orderData.financialEntry === '1';

      this.submit_data.contract_data = result.orderData;
      this.submit_data.orderCode = result.orderData.orderCode;
      this.submit_data.orderId = result.orderData.orderId;
      this.submit_data.orderDetailId = result.orderData.orderDetailId;
      this.submit_data.orderCodeRelate = result.orderData.orderCodeRelate;
    },
    // 组件回调
    onSupplierAndContractChange(val) {
      this.submit_data.supplier_data.supplierCode = val.supplierCode;
      this.submit_data.supplier_data.supplierName = val.supplierName;
      this.submit_data.contract_data = val.contract || val;
      this.busModel = this.submit_data.contract_data.busModel;
      this.submit_data.busModel = this.submit_data.contract_data.busModel;
      if (!this.routerParams.orderId) {
        this.submit_data.return_type_name =
          this.submit_data.busModel === '2' ? '1' : '';
      }
      if (this.routerParams.orderId) {
        if (this.jsTypes !== null) {
          this.submit_data.return_type_name = this.jsTypes === 2 ? '2' : '1';
        } else {
          this.submit_data.return_type_name =
            this.submit_data.busModel === '2' ? '1' : '';
        }
      }
      // 清空product
      if (!this.status.isFirstMount) {
        this.submit_data.return_goods = [];
      }
    },
    // 切换退货类型清空退货列表
    changeSelectItem() {
      // if (this.submit_data.return_goods.length > 0) {
      //   this.$confirm('切换退货类型将会清空退货产品，是否继续？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      // this.submit_data.return_type_name = val;
      this.submit_data.return_goods = [];
      //     this.$message({
      //       type: 'success',
      //       message: '切换成功!'
      //     });
      //   });
      // }
    },
    getOrderTypeRowsByEdit(result) {
      this.$axios({
        method: 'post',
        url: getOrderType,
        data: {
          busModel: result.orderData.busModel,
          supplierCode: '000'
        }
      }).then(res => {
        const newResult = res.data.payload || {};
        this.render_data.order_type_rows = newResult;
        this.submit_data.order_type_key = this.render_data.order_type_rows.find(
          item => item.orderTypeName.includes('退货')
        ).ddbm;
      });
    },
    getOrderTypeRows(res) {
      this.render_data.order_type_rows = res;
      this.submit_data.order_type_key = this.render_data.order_type_rows.find(
        item => item.orderTypeName.includes('退货')
      ).ddbm;
    },
    // getChangeItem(val) {
    //   this.submit_data.return_type_all = val;
    // },
    getSeledAddress(val) {
      this.submit_data.full_address = val;
    },
    // 全局性初始化配置
    // 导航栏按钮
    // 上一步
    onPrev() {
      if (this.active_index-- <= 1) this.active_index = 1;
      this.initGlobalBtn();
    },
    // 下一步
    onNext() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.submit_data
      );
      if (verifyResult.pass === true) {
        if (this.active_index++ >= 3) this.active_index = 3;
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
      this.initGlobalBtn();
    },
    // 暂存
    onSaveDraft() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.submit_data
      );
      if (verifyResult.pass === true) {
        this.saveProgress();
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
    },
    saveProgress: throttle(
      // eslint-disable-next-line func-names
      function() {
        // this.saveTheData();
        this.$axios({
          url: saveOrderReturn,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            const order = isObject(res.data.payload) ? res.data.payload : {};
            this.submit_data.orderId = order.orderId;
            this.submit_data.orderDetailId = order.orderDetailId;
            this.submit_data.orderCode = order.orderCode;
            this.$message({
              type: 'success',
              message: '暂存成功'
            });
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: '暂存失败'
            });
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    reStructSubmitData() {
      return {
        busModel: this.busModel,
        jsType:
          this.submit_data.return_type_name && this.busModel === '2'
            ? Number(this.submit_data.return_type_name)
            : null,
        // 只有当busModel为1，即批发退货的时候才传以下两个字段
        financialEntry:
          this.busModel === '1'
            ? this.submit_data.invoice_info.financial_entry
              ? '1'
              : '2'
            : '',
        receiptInvoice:
          this.busModel === '1'
            ? this.submit_data.invoice_info.receive_invoice
              ? '1'
              : '2'
            : '',
        // end
        returnReasonCode: this.submit_data.return_reason.reason_sel,
        returnReason: this.submit_data.return_reason.reason_name,
        returnReasonDetail: this.submit_data.return_reason.reason_text,
        supplierVo: {
          vendorCode: this.submit_data.supplier_data.supplierCode,
          vendorName: this.submit_data.supplier_data.supplierName
        }, // 供应商
        contractVo: {
          ...this.submit_data.contract_data,
          marketCode: this.submit_data.contract_data.channelType,
          supplierCode: this.submit_data.contract_data.originalFactoryCode,
          supplierName: this.submit_data.contract_data.originalFactoryName
        }, // 合同
        saveProductVO: this.submit_data.return_goods, // 采购产品
        addressResDto: this.submit_data.full_address, // 地址
        commonFileForms: this.submit_data.return_reason.reason_imgs.map(
          item => {
            const name = item.substring(item.lastIndexOf('/') + 1);
            return {
              fileName: name.split('.')[0],
              fileType: name.split('.')[1],
              fileUrl: item
            };
          }
        ), // 原因图片
        orderCode: this.submit_data.orderCode, // 订单编码
        orderDetailId: this.submit_data.orderDetailId, // 订单详情id
        orderId: this.submit_data.orderId, // 订单id
        orderTypeId: this.render_data.order_type_rows.find(
          item => item.ddbm === this.submit_data.order_type_key
        ).orderTypeId,
        orderType: this.submit_data.order_type_key,
        orderCodeRelate: '',
        createType: 1 // 1独立创建，2原单创建
      };
    },
    onSubmit: throttle(
      // eslint-disable-next-line func-names
      function() {
        // if (this.submit_data.transportType === '1') {
        //   this.submit_data.addressResDto = {};
        // } else {
        //   this.submit_data.addressResDto = this.storageAddress;
        // }
        this.submit_loading = true;
        this.$axios({
          url: submitOrderReturn,
          method: 'post',
          data: this.reStructSubmitData()
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$router.push('/after-sale/order-management');
              this.$message({
                message: '订单提交成功',
                type: 'success'
              });
            }
          })
          .catch(err => {
            if (err.data.code === '200001') {
              this.$router.push('/after-sale/order-management');
            }
          })
          .finally(() => {
            this.status.dialogVisible = false;
            this.status.submit_loading = false;
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    // 打开确认提交弹窗
    showConfirmDialog() {
      const verifyResult = indexService.verifyStep(3, this.submit_data);
      if (verifyResult.pass === true) {
        this.status.dialogVisible = true;
        // this.saveTheData();
      } else {
        this.$notify({
          title: '必填项',
          message: verifyResult.message,
          type: 'warning'
        });
      }
    },
    initGlobalBtn() {
      const btnObj = {
        type: 'btn',
        arr: []
      };
      const saveDraftBtn = {
        val: '暂存',
        handle: this.onSaveDraft
      };
      const prevBtn = {
        type: 'primary',
        val: '上一步',
        handle: this.onPrev
      };
      const nextBtn = {
        type: 'primary',
        val: '下一步',
        handle: this.onNext
      };
      const submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.showConfirmDialog
      };
      if (this.active_index !== 1) {
        btnObj.arr.push(prevBtn);
      }
      if (this.active_index !== 3) {
        btnObj.arr.push(nextBtn);
      } else {
        btnObj.arr.push(submitBtn);
      }
      btnObj.arr.push(saveDraftBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    // 纯数据的转换和处理
    // saveTheData() {
    //   // 通过sync和update更新products数据，所以这里要赋值以下，该操作意图等同于onSupplierAndContractChange方法。
    //   // 赋值第二步选择产品部分数据
    //   this.submit_data.saveProductVO = this.form_data.products;
    //   // 复制第三步的三个选项部分（订单类型，承运方式，支付方式，以及备注）
    //   this.submit_data.orderTypeId = this.form_data.ordertype; // 订单类型
    //   this.submit_data.orderType = '';
    //   this.submit_data.transportType = this.form_data.carryway; // 承运方式
    //   this.submit_data.payType = this.form_data.payway; // 支付方式
    //   this.submit_data.remark = this.form_data.remark; // 备注

    //   // 这里，要把expand动态生成的表单，组合成后端想要的数据格式，也就是说，要再反向重组一下。
    //   let extendResult = this.base_extend_data;
    //   extendResult.forEach(item => {
    //     item.attributeValue = this.form_data.extend[item.attributeNameValue] || '';
    //   });
    //   this.submit_data.orderAppendPOS = extendResult;
    //   if (this.submit_data.transportType === '1') {
    //     this.submit_data.addressResDto = {};
    //   } else {
    //     this.submit_data.addressResDto = this.storageAddress;
    //   }
    // },
    getReasonName(reasonName) {
      this.submit_data.return_reason.reason_name = reasonName;
    },
    splitSubmitDataBySteps() {
      const curStep = this.active_index; // 当前步骤
      // 这里跟submit_data一模一样，下面选择性的赋值
      const splitSubmitData = {
        busModel: this.busModel,
        jsType:
          this.submit_data.return_type_name && this.busModel === '2'
            ? Number(this.submit_data.return_type_name)
            : null,
        financialEntry: '',
        receiptInvoice: '',
        returnReason: '',
        returnReasonCode: '',
        returnReasonDetail: '',
        supplierVo: {}, // 供应商
        contractVo: {}, // 合同
        saveProductVO: [], // 采购产品
        addressResDto: {}, // 地址
        commonFileForms: [], // 原因图片
        orderCode: this.submit_data.orderCode, // 订单编码
        orderDetailId: this.submit_data.orderDetailId, // 订单详情id
        orderId: this.submit_data.orderId, // 订单id
        orderTypeId: this.render_data.order_type_rows.find(
          item => item.ddbm === this.submit_data.order_type_key
        ).orderTypeId,
        orderType: this.submit_data.order_type_key,
        orderCodeRelate: '',
        createType: 1 // 1独立创建，2原单创建
      };
      // 第一步
      // eslint-disable-next-line default-case
      switch (curStep) {
        // 第一步，只存第一步的合同和供应商
        case 1:
          splitSubmitData.supplierVo = {
            vendorCode: this.submit_data.supplier_data.supplierCode,
            vendorName: this.submit_data.supplier_data.supplierName
          };
          splitSubmitData.contractVo = {
            ...this.submit_data.contract_data,
            marketCode: this.submit_data.contract_data.channelType,
            supplierCode: this.submit_data.contract_data.originalFactoryCode,
            supplierName: this.submit_data.contract_data.originalFactoryName
          };
          break;
        // 除了第一步的，还额外需要产品部分
        case 2:
          splitSubmitData.supplierVo = {
            vendorCode: this.submit_data.supplier_data.supplierCode,
            vendorName: this.submit_data.supplier_data.supplierName
          };
          splitSubmitData.contractVo = {
            ...this.submit_data.contract_data,
            marketCode: this.submit_data.contract_data.channelType,
            supplierCode: this.submit_data.contract_data.originalFactoryCode,
            supplierName: this.submit_data.contract_data.originalFactoryName
          };
          splitSubmitData.saveProductVO = this.submit_data.return_goods;
          splitSubmitData.returnReasonCode = this.submit_data.return_reason.reason_sel;
          splitSubmitData.returnReason = this.submit_data.return_reason.reason_name;
          splitSubmitData.returnReasonDetail = this.submit_data.return_reason.reason_text;
          splitSubmitData.commonFileForms = this.submit_data.return_reason.reason_imgs.map(
            item => {
              const name = item.substring(item.lastIndexOf('/') + 1);
              return {
                fileName: name.split('.')[0],
                fileType: name.split('.')[1],
                fileUrl: item
              };
            }
          );

          break;
        // 第三步就比较简单了
        case 3:
          splitSubmitData.supplierVo = {
            vendorCode: this.submit_data.supplier_data.supplierCode,
            vendorName: this.submit_data.supplier_data.supplierName
          };
          splitSubmitData.contractVo = {
            ...this.submit_data.contract_data,
            marketCode: this.submit_data.contract_data.channelType,
            supplierCode: this.submit_data.contract_data.originalFactoryCode,
            supplierName: this.submit_data.contract_data.originalFactoryName
          };
          splitSubmitData.saveProductVO = this.submit_data.return_goods;
          splitSubmitData.returnReasonCode = this.submit_data.return_reason.reason_sel;
          splitSubmitData.returnReason = this.submit_data.return_reason.reason_name;
          splitSubmitData.returnReasonDetail = this.submit_data.return_reason.reason_text;
          splitSubmitData.addressResDto = this.submit_data.full_address;
          // 只有当busModel为1，即批发退货的时候才传以下两个字段
          splitSubmitData.financialEntry =
            this.busModel === '1'
              ? this.submit_data.invoice_info.financial_entry
                ? '1'
                : '2'
              : '';
          splitSubmitData.receiptInvoice =
            this.busModel === '1'
              ? this.submit_data.invoice_info.receive_invoice
                ? '1'
                : '2'
              : '';
          // end
          splitSubmitData.commonFileForms = this.submit_data.return_reason.reason_imgs.map(
            item => {
              const name = item.substring(item.lastIndexOf('/') + 1);
              return {
                fileName: name.split('.')[0],
                fileType: name.split('.')[1],
                fileUrl: item
              };
            }
          );
          break;
      }
      return splitSubmitData;
    }
  }
};
